/**
 * All Rights Reserved.
 * This software is the confidential and proprietary information of
 * Beijing Audiotone Technology Co.,Ltd.
 * ("Confidential Information"). You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 * the terms of the license agreement you entered into with Audiotone.
 * AUDIOTONE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. AUDIOTONE SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */
package pro.uccs.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import pro.uccs.constant.ISVErrorOauthCode;
import pro.uccs.constant.OpenPlatformConstant;
import pro.uccs.service.Oauth2Service;
import pro.uccs.util.Coder;
import pro.uccs.util.EncryptUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @author songc
 */
@Controller
@RequestMapping("/open")
public class RequestResourceController {

    private Oauth2Service openOauth2Service;
    /**
     * 普通授权模型获取资源
     * 获取当前用户信息
     *
     * @return 个人用户信息
     * @throws IOException
     */
    @RequestMapping(value = "/getResourceByAuthorizationUserInfo", method = RequestMethod.GET,produces="text/html;charset=UTF-8")
    @ResponseBody
    public Object getResourceByAuthorizationUserInfo() throws IOException {
        HttpServletRequest httpServletRequest =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String error = httpServletRequest.getParameter("error");
        String error_description = httpServletRequest.getParameter("error_description");
        String state = httpServletRequest.getParameter("state");
        Object obj = null;
        //授权服务回调,异常信息
        if(!StringUtils.isEmpty(error) && error.equals(ISVErrorOauthCode.AUTHORIZE_LOGIN_CANCLE.code())){
            System.out.println("用户取消登录");
            obj = ISVErrorOauthCode.AUTHORIZE_LOGIN_CANCLE.message();
        }else{
            /**
             * 调用资源接口，具体请查看资源列表
             */
            String method = "simba.user.info";
            String clientId = OpenPlatformConstant.CLIENT_ID;
            Map<String, String> params = new HashMap<>(4);

            params.put("method", method);

            params.put("client_id", OpenPlatformConstant.CLIENT_ID);

            params.put("session", OpenPlatformConstant.SESSION);

            String timestamp = String.valueOf(System.currentTimeMillis());
            params.put("timestamp", timestamp);
            /**
             * 参数加密，防止参数被篡改
             * 采用key值排序后MD5加密
             */
            String sign = EncryptUtil.paramSign(params, OpenPlatformConstant.CLIENT_SECRET, Coder.KEY_MD5);
            System.out.println(timestamp);
            System.out.println(sign);
            obj = openOauth2Service.getResourceByAuthorizationUserInfo(sign, method, clientId, OpenPlatformConstant.SESSION, timestamp,null);
            System.out.println(JSON.toJSONString(obj));
        }
        return obj;
    }
    /**
     * 普通授权模型获取资源
     * 获取当前用户信息
     *
     * @return 个人用户信息
     * @throws IOException
     */
    @RequestMapping(value = "/getResourceByAuthorization", method = RequestMethod.GET)
    @ResponseBody
    public Object getResourceByAuthorization() throws IOException {
        HttpServletRequest httpServletRequest =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String error = httpServletRequest.getParameter("error");
        String error_description = httpServletRequest.getParameter("error_description");
        String state = httpServletRequest.getParameter("state");
        Object obj = null;
        //授权服务回调,异常信息
        if(!StringUtils.isEmpty(error) && error.equals(ISVErrorOauthCode.AUTHORIZE_LOGIN_CANCLE.code())){
            System.out.println("用户取消登录");
            obj = ISVErrorOauthCode.AUTHORIZE_LOGIN_CANCLE.message();
        }else{
            /**
             * 调用资源接口，具体请查看资源列表
             */
//            String method = "simba.user.info";
            String method = "simba.enterprise.info";
            String clientId = OpenPlatformConstant.CLIENT_ID;

            Map<String, String> params = new HashMap<>(4);

            params.put("method", method);

            params.put("client_id", OpenPlatformConstant.CLIENT_ID);

            params.put("session", OpenPlatformConstant.SESSION);


            String timestamp = String.valueOf(System.currentTimeMillis());
            params.put("timestamp", timestamp);
            String param_json = "{\"userNumbers\":[70002253]}";
            params.put("param_json", param_json);
            /**
             * 参数加密，防止参数被篡改
             * 采用key值排序后MD5加密
             */
            String sign = EncryptUtil.paramSign(params, OpenPlatformConstant.CLIENT_SECRET, Coder.KEY_MD5);

            obj = openOauth2Service.getResourceByAuthorization(sign, method, clientId, OpenPlatformConstant.SESSION, timestamp,param_json);
        }



        return obj;
    }

    /**
     * 通过快速授权用户获取授权码
     *
     * @return
     */
    @RequestMapping(value = "/getAuthorizationCodeByQuickAuthorization", method = RequestMethod.GET,produces="text/html;charset=UTF-8")
    @ResponseBody
    public String getAuthorizationCodeByQuickAuthorization(String hashKey,String token ) {
        /**
         * 终端临时生成hashkey 用于快速授权认证
         */
//        String hashKey = "X4Ar2NlkhSiddDMq";

        String clientId = OpenPlatformConstant.CLIENT_ID;
        /**
         * 终端token，用于标识用户登陆信息
         */
//        String token = "a0exmpitf35dbonn";
        /**
         * 企业id 定位快速授权的企业字段
         */
        String enterpriseId = "235604";

        String code = openOauth2Service.getAuthorizationCodeByQuickAuthorization(hashKey, clientId, token, enterpriseId);

        return code;
    }

    /**
     * 通过授权码进行资源访问
     *
     * @return
     */
    @RequestMapping(value = "/getResourceByAuthorizationCode", method = RequestMethod.GET)
    @ResponseBody
    public String getResourceByAuthorizationCode(String code) throws IOException {
        String method = "simba.user.info";

        String clientId = OpenPlatformConstant.CLIENT_ID;
        Map<String, String> params = new HashMap<>(4);
        params.put("method", method);
        params.put("client_id", OpenPlatformConstant.CLIENT_ID);
        params.put("session", OpenPlatformConstant.SESSION);
        String timestamp = String.valueOf(System.currentTimeMillis());
        params.put("timestamp", timestamp);

        /**
         * 参数加密，防止参数被篡改
         * 采用key值排序后MD5加密
         */
        String sign = EncryptUtil.paramSign(params, OpenPlatformConstant.CLIENT_SECRET, Coder.KEY_MD5);
        String result = openOauth2Service.getResourceByAuthorizationCode(code, sign, method, clientId, OpenPlatformConstant.SESSION, timestamp);
        return result;
    }


    @RequestMapping(value = "/getResourceByAccessToken", method = RequestMethod.GET)
    @ResponseBody
    public String getResourceByAccessToken(String accessToken) throws IOException {
        /**
         * 资源访问令牌
         */
        String method = "simba.user.info";

        String clientId = OpenPlatformConstant.CLIENT_ID;
        Map<String, String> params = new HashMap<>(4);
        params.put("method", method);
        params.put("client_id", OpenPlatformConstant.CLIENT_ID);
        params.put("session", OpenPlatformConstant.SESSION);
        String timestamp = String.valueOf(System.currentTimeMillis());
        params.put("timestamp", timestamp);

        /**
         * 参数加密，防止参数被篡改
         * 采用key值排序后MD5加密
         */
        String sign = EncryptUtil.paramSign(params, OpenPlatformConstant.CLIENT_SECRET, Coder.KEY_MD5);
        String obj = openOauth2Service.getResourceByAccessToken(accessToken,sign,method,clientId,OpenPlatformConstant.SESSION,timestamp);
        return obj;
    }


    public void setOpenOauth2Service(Oauth2Service openOauth2Service) {
        this.openOauth2Service = openOauth2Service;
    }
}
